﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TemplateAddIn
{
    public partial class VariableFillUI : Form
    {
        VariableList<Variable> varDictionary;
        VariableList<Variable> changedVariables;
        DataTable variables;

        public VariableFillUI(VariableList<Variable> varList)
        {
            InitializeComponent();

            this.varDictionary = new VariableList<Variable>();
            this.changedVariables = new VariableList<Variable>();

            foreach (Variable v in varList.Values)
            {
                if (v.VariableType == Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlText)
                    varDictionary.Add(v);
            }            
        }

        private void btnApply_Click(object sender, EventArgs e)
        {
            foreach (TextVariable var in changedVariables.Values)
            {
                varDictionary[var.Name].SetContent(var.Content);
            }

            this.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void VariableFillUI_Load(object sender, EventArgs e)
        {
            DataColumn names = new DataColumn("Name");
            DataColumn text = new DataColumn("Content");
            DataRow row;

            names.ReadOnly = true;

            variables = new DataTable();
            variables.Columns.Add(names);
            variables.Columns.Add(text);

            foreach (TextVariable var in varDictionary.Values)
            {
                row = variables.NewRow();

                row[names] = var.Name;
                row[text] = var.Content;

                variables.Rows.Add(row);
            }

            dgvVariables.DataSource = variables;
        }

        private void dgvVariables_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (!changedVariables.Keys.Contains<string>(variables.Rows[e.RowIndex][0].ToString()))
            {
                changedVariables.Add(variables.Rows[e.RowIndex][0].ToString(), new TextVariable(variables.Rows[e.RowIndex][0].ToString(), variables.Rows[e.RowIndex][1].ToString()));
            }
            else
            {
                changedVariables[variables.Rows[e.RowIndex][0].ToString()].SetContent(variables.Rows[e.RowIndex][1].ToString());
            }
        }
    }
}
